<?php

namespace App\Http\Controllers;

use App\Models\ForumCategory;
use App\Models\ForumTopic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ForumTopicRequest;
use App\Handlers\ImageUploadHandler;
use Auth;

class ForumTopicsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }

	public function index(Request $request, ForumTopic $topic)
	{
		$forum_topics = $topic->withOrder($request->order)->paginate(30);
        $forum_categorys=ForumCategory::all();
		return view('forum.forum_topics.index', compact('forum_topics','forum_categorys'));
	}

    public function show(Request $request,ForumTopic $topic)
    {
        // URL 矫正
        if ( ! empty($topic->slug) && $topic->slug != $request->slug) {
            return redirect($topic->link(), 301);
        }
        return view('forum.forum_topics.show', compact('topic'));
    }

	public function create(ForumTopic $forum_topic )
	{
        $categories = ForumCategory::all();
		return view('forum.forum_topics.create_and_edit', compact('forum_topic','categories'));
	}

	public function store(ForumTopicRequest $request,ForumTopic $forum_topic)
	{
        $forum_topic->fill($request->all());
        $forum_topic->user_id = Auth::id();//当前id
        $forum_topic->save();

        return redirect()->to($forum_topic->link())->with('message', '发帖成功!');
	}

	public function edit(ForumTopic $forum_topic)
	{
        $this->authorize('update', $forum_topic);
        $categories = ForumCategory::all();
		return view('forum.forum_topics.create_and_edit', compact('forum_topic','categories'));
	}

	public function update(ForumTopicRequest $request, ForumTopic $forum_topic)
	{
		$this->authorize('update', $forum_topic);
		$forum_topic->update($request->all());

		return redirect()->to($forum_topic->link())->with('message', '修改成功');
	}

	public function destroy(ForumTopic $forum_topic)
	{

		$this->authorize('destroy', $forum_topic);
		$forum_topic->delete();

		return redirect()->route('topics.index')->with('message', '删除成功');
	}

	//发帖上传图片
    public function uploadImage(Request $request, ImageUploadHandler $uploader)
    {
        // 初始化返回数据，默认是失败的
        $data = [
            'success'   => false,
            'msg'       => '上传失败!',
            'file_path' => ''
        ];
        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->upload_file) {
            // 保存图片到本地
            $result = $uploader->save($request->upload_file, 'forum_topics', \Auth::id(), 1024);
            // 图片保存成功的话
            if ($result) {
                $data['file_path'] = $result['path'];
                $data['msg']       = "上传成功!";
                $data['success']   = true;
            }
        }
        return $data;
    }
}